package com.hmh.student.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmh.student.system.entity.SysRoleMenu;
import com.hmh.student.system.entity.SysUserRole;
import com.hmh.student.system.mapper.SysUserRoleMapper;
import com.hmh.student.system.service.ISysRoleService;
import com.hmh.student.system.service.ISysUserRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmh.student.system.service.ISysUserService;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author xyf
 * @since 2025-04-09
 */
@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements ISysUserRoleService {

    @Autowired
   private ISysUserService sysUserService;
    @Autowired
   private ISysRoleService sysRoleService;

    @Override
    public Page<SysUserRole> queryUserRolepage(Integer userId, Integer roleId, Integer current, Integer pageSize) {
        QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<>();
        if (userId != null) {
            queryWrapper.like("user_id", userId);
        }
        if (roleId != null) {
            queryWrapper.like("role_id", roleId);
        }
        return page(new Page<>(current, pageSize), queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void assignRoleToUser(Integer userId, Integer roleId) {
        // 参数校验
        if (userId == null || roleId == null) {
            throw new IllegalArgumentException("参数不能为空");
        }

        // 检查用户和角色是否存在
        if (!sysUserService.existsById(userId)) {
            throw new IllegalArgumentException("用户不存在");
        }
        if (!sysRoleService.existsById(roleId)) {
            throw new IllegalArgumentException("角色不存在");
        }

        // 删除旧角色并分配新角色
        this.lambdaUpdate()
                .eq(SysUserRole::getUserId, userId)
                .remove();

        SysUserRole userRole = new SysUserRole();
        userRole.setUserId(userId);
        userRole.setRoleId(roleId);
        this.save(userRole);
    }

    @Override
    public Integer getRoleByUserId(Integer userId) {
        if (userId == null) {
            throw new IllegalArgumentException("用户ID不能为空");
        }
        SysUserRole userRole = this.lambdaQuery()
                .eq(SysUserRole::getUserId, userId)
                .one();
        return userRole != null ? userRole.getRoleId() : null;
    }

}
